package funcInterface.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

class Person {
    private int age;
    private String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


/**
 * 理解lambda传递行为
 */
public class Action {
    public static void main(String[] args) {
        Action action = new Action();
        Person person1 = new Person(20, "maomao");
        Person person2 = new Person(30, "mayun");
        Person person3 = new Person(26, "keke");

        List<Person> persons = new ArrayList<Person>() {
            {
                add(person1);
                add(person2);
                add(person3);
            }
        };

        // 需求：过滤出姓名是keke的人
//        List<Person> old = action.getPersonByName("keke", persons);
//        old.forEach(person -> System.out.println(person.getName()));

//        List<Person> widthLambda = action.getPersonByName2("maomao", persons);
//        widthLambda.forEach(person -> System.out.println(person.getName()));

        List<Person> biFuncation = action.getPerson(21, persons, (age, personList) -> personList
                .stream().filter(person -> person.getAge() < age).collect(Collectors.toList()));
        biFuncation.forEach(person -> System.out.println(person.getName()));
    }

    /**
     * 最古老的写法
     *
     * @param name
     * @param personList
     * @return
     */
    public List<Person> getPersonByName(String name, List<Person> personList) {
        List<Person> list = new ArrayList<>();
        for (Person person : personList) {
            if (person.getName().equals(name)) {
                list.add(person);
            }
        }
        return list;
    }

    /**
     * lambda+stream
     *
     * @param name
     * @param personList
     * @return
     */
    public List<Person> getPersonByName2(String name, List<Person> personList) {
        return personList.stream().filter(person -> person.getName().equals(name)).collect(Collectors.toList());
    }

    /**
     * 不在实现具体的行为，把行为交给调用者实现
     *
     * @param age
     * @param personList
     * @param biFunction
     * @return
     */
    public List<Person> getPerson(int age, List<Person> personList, BiFunction<Integer, List<Person>, List<Person>> biFunction) {
        return biFunction.apply(age, personList);
    }
}
